package org.example.web_maven.dao;
import org.example.web_maven.entity.Users;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class UsersDao {
    public List<Users> getList() throws Exception{
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        // 获取数据库的链接
        Connection conn =  DriverManager.getConnection("jdbc:mysql://localhost:3306/test_maven?useUnicode=true&characterEncoding=utf8",
                "root", "");
        // 准备pstmt对象
        PreparedStatement pstmt =  conn.prepareStatement("select * from users ");
        // 执行sql语句
        ResultSet rs =  pstmt.executeQuery();
        // 循环获取数据
        List<Users> list = new ArrayList<>();
        while (rs.next()){
            Users u = new Users();
            u.setId(rs.getInt("id"));
            u.setUsername(rs.getString("username"));
            u.setAge(rs.getInt("age"));
            u.setBirth(rs.getTimestamp("birth"));
            list.add(u);
        }
        rs.close();
        conn.close();
        return list;
    }
    /**
     * 保存用户
     * @param user
     */
    public void save(Users user) {
        try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 获取数据库的链接
            Connection conn =  DriverManager.getConnection("jdbc:mysql://localhost:3306/test_maven?useUnicode=true&characterEncoding=utf8",
                    "root", "");
            String sql = "insert into users(username,age,birth) values(?,?,?)";
            // 预编译sql语句
            PreparedStatement pstmt =  conn.prepareStatement(sql);
            // 给占位符赋值
            pstmt.setString(1,user.getUsername());
            pstmt.setInt(2,user.getAge());
            pstmt.setObject(3,user.getBirth());
            // 执行sql
            pstmt.executeUpdate();// delete update insert
            // 如果保存到额数据中文有乱码 创建数据库的时候没有指定 编码格式
            conn.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
